/*
 * Copyright 2013-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.cyx.netty.gateway.handler.predicate;
import com.alibaba.fastjson.JSON;
import com.cyx.netty.gateway.handler.support.RoutePredicateFactoryUtils;
import com.cyx.netty.gateway.support.ServerWebExchange;
import com.cyx.netty.gateway.util.UriComponentsBuilder;
import com.cyx.netty.gateway.util.pattern.PathPattern;
import com.cyx.netty.gateway.util.pattern.PathPatternParser;
//import com.cyx.netty.gateway.util.server.PathContainer;
import com.cyx.netty.gateway.util.server.PathContainer;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.tuple.Tuple;

@Slf4j
public class PathRoutePredicateFactory implements RoutePredicateFactory {

	private final PathPatternParser pathPatternParser = new PathPatternParser();

	@Override
	public List<String> argNames() {
		return Collections.singletonList(PATTERN_KEY);
	}

	@Override
	public Predicate<ServerWebExchange> apply(Tuple args) {
		String unParsedPattern = args.getString(PATTERN_KEY);
		PathPattern pattern;
		synchronized (this.pathPatternParser) {
			pattern = this.pathPatternParser.parse(unParsedPattern);
		}

		log.info("PathRoutePredicateFactory: apply "+unParsedPattern+"\n");
//HttpWebHandlerAdapter createExchange
		return exchange -> {

			URI toUri = UriComponentsBuilder.fromUriString(exchange.getRequest().uri()).build(true).toUri();
			boolean match = pattern.matches(PathContainer.parsePath(toUri.getPath()));

			log.info("PathRoutePredicateFactory: apply exchange:"+match);

//			RoutePredicateFactoryUtils.traceMatch("Pattern", pattern.getPatternString(), toUri.getPath(), match);
			if(match) {
				return true;
			}
			return false;
		};
	}
}
